package util

import (
	"compress/gzip"
	"crypto/tls"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"strings"
)

//HTTPRequest 请求数据
func HTTPRequest(method, address, payLoad string, header, formParam, queryParam map[string]string) ([]byte, error) {

	// proxy, _ := url.Parse("http://127.0.0.1:8888")
	tr := &http.Transport{
		// Proxy:           http.ProxyURL(proxy),
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}

	client := &http.Client{Transport: tr}
	if formParam != nil {
		paramStr := ""
		for k, v := range formParam {
			if len(paramStr) == 0 {
				paramStr = paramStr + k + "=" + url.QueryEscape(v)
			} else {
				paramStr = paramStr + "&" + k + "=" + url.QueryEscape(v)
			}
		}
		if len(paramStr) > 0 {
			payLoad = paramStr
		}
	}

	req, err := http.NewRequest(method, address, strings.NewReader(payLoad))
	if err != nil {
		log.Println(err)
	}
	req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36")
	req.Header.Set("Content-Type", "application/json;charset=UTF-8")
	req.Header.Set("Accept", "*/*")
	if method == "POST" {
		req.Header.Set("Accept-Encoding", "gzip, deflate")
	}
	req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
	req.Header.Set("Connection", "keep-alive")
	req.Header.Set("Content-Length", "60")
	req.Header.Set("Pragma", "no-cache")
	req.Header.Set("X-Requested-With", "XMLHttpRequest")

	for k, v := range header {
		req.Header.Set(k, v)
	}
	for k, v := range queryParam {
		q := req.URL.Query()
		q.Add(k, v)
		req.URL.RawQuery = q.Encode()
	}

	res, err := client.Do(req)
	if err != nil {
		log.Println(err)
	}
	if res == nil {
		return nil, nil
	}
	defer res.Body.Close()
	var result []byte
	if strings.Contains(strings.Join(res.Header["Content-Encoding"], ""), "gzip") {
		read, err := gzip.NewReader(res.Body)
		if err != nil {
			log.Println(err)
		}
		result, err = ioutil.ReadAll(read)
	} else {
		result, err = ioutil.ReadAll(res.Body)
	}
	return result, err
}
